package com.zxs.cart.service.impl;

import client.ProductClient;
import com.zxs.cart.mapper.CartMapper;
import com.zxs.cart.service.CartService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import parm.CartParam;
import parm.ProductIdParam;
import parm.ProductIdsParam;
import pojo.Cart;
import pojo.CartVo;
import pojo.Product;
import utils.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zxs
 * *8 19:55
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductClient productClient;

    @Override
    public R save(CartParam cartParam) {




        //1 检查是否还有库存
        ProductIdParam productIdParam = new ProductIdParam();
        productIdParam.setProductId(cartParam.getProductId());
        Product product = productClient.cartDetail(productIdParam);
        System.out.println("product = " + product);
        if (product == null) {
            return R.fail("商品已经被删除，无法添加到购物车");
        }
        if (product.getProductNum() <= 0) {
            R fail = R.fail("没有库存了，无法添加到购物车");
            fail.setCode("003");
            return fail;
        }
        //2 检查是否已经添加过购物车
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", cartParam.getUserId());
        queryWrapper.eq("product_id", cartParam.getProductId());

        Cart cart = cartMapper.selectOne(queryWrapper);
        System.out.println("cart = " + cart);
        if (cart != null) {
            if (cart.getNum() >= product.getProductNum()){
                return R.fail("购物车数量大于库存！");
            }
            //购物车里有，则数量加一
            cart.setNum(cart.getNum() + 1);
            //更新数据库
            cartMapper.updateById(cart);
            R ok = R.ok("购物车存在该商品，数量+1");
            ok.setCode("002");
            return ok;
        }

        //3 添加到购物车
        Cart cart1 = new Cart();
        cart1.setNum(1);
        cart1.setUserId(cartParam.getUserId());
        cart1.setProductId(cartParam.getProductId());
        cartMapper.insert(cart1);


        //4 将product和cart 封装成前端需要的对象并返回
        CartVo cartVo = new CartVo(product, cart1);

        return R.ok("购物车添加成功！", cartVo);
    }

    /**
     * 根据用户id获取购物车的商品集合
     *
     * @param userId
     * @return
     */
    @Override
    public R list(Integer userId) {
        //1 根据用户id查询购物车的商品对象集合
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        List<Cart> carts = cartMapper.selectList(queryWrapper);
        //如果购物车为空
        if (carts == null || carts.size() == 0) {
            carts = new ArrayList<>();
            return R.ok("购物车空空如也！", carts);
        }
        //根据商品对象集合得到商品id集合
        List<Integer> productids = new ArrayList<>();
        for (Cart cart : carts) {
            productids.add(cart.getProductId());
        }
        //封装参数远程调用productClient获取商品内容集合
        ProductIdsParam productIdsParam = new ProductIdsParam();
        productIdsParam.setProductIds(productids);
        List<Product> products = productClient.cartList(productIdsParam);

        List<CartVo> cartVos = new ArrayList<>();
        Map<Integer, Product> productMap = products.stream().collect(Collectors.toMap(Product::getProductId, v -> v));

        for (Cart cart : carts) {
            CartVo cartVo = new CartVo(productMap.get(cart.getProductId()), cart);
            cartVos.add(cartVo);
        }
        R ok = R.ok("购物车查询数据成功！", cartVos);
        log.info("购物车查询数据成功", cartVos);
        return ok;
    }

    /**
     * 修改购物车里的商品数量
     *
     * @param cart
     * @return
     */
    @Override
    public R update(Cart cart) {
        //exp 修改数量之前先根据商品id查询商品数量
        ProductIdParam productIdParam = new ProductIdParam();
        productIdParam.setProductId(cart.getProductId());
        Product product = productClient.cartDetail(productIdParam);
        //exp 如果修改的数量大于商品库存数量，则返回添加数量失败
        if (cart.getNum() > product.getProductNum()) {
            return R.fail("数量大于商品库存数量,添加数量失败!");
        }
        //exp 如果大于，然后对数据库的商品数量进行修改
        //exp 具体修改购物车中哪个商品
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", cart.getUserId());
        queryWrapper.eq("product_id", cart.getProductId());
        Cart newCart = cartMapper.selectOne(queryWrapper);
        newCart.setNum(cart.getNum());
        int i = cartMapper.updateById(newCart);
        return R.ok("修改购物车数量成功！");
    }

    /**
     * 删除购物车
     *
     * @param cart
     * @return
     */
    @Override
    public R remove(Cart cart) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", cart.getUserId());
        queryWrapper.eq("product_id", cart.getProductId());
        int delete = cartMapper.delete(queryWrapper);
        if (delete == 0) {
            return R.fail("删除购物车失败");
        }
        log.info("删除购物车:", delete);
        return R.ok("删除购物车成功");
    }

    /**
     * 订单后，批量清空购物车id
     *
     * @param cartIds
     */
    @Override
    public void clear(List<Integer> cartIds) {
        cartMapper.deleteBatchIds(cartIds);
        log.info("CartServiceImpl.clearIds业务结束， 结果:{}", cartIds);
    }

    /**
     * 后台删除时检查购物车表中是否有用户引用
     *
     * @param productId
     * @return
     */
    @Override
    public R checkProduct(Integer productId) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);

        Long count = cartMapper.selectCount(queryWrapper);
        if (count == 0) {
            return R.ok("购物车中不存在要删除的商品!");
        }
        return R.fail("购物车中存在要删除的商品!");
    }
}
